import validate from '../../libs/validate';

const appVideoEditBtn = (h, param, vm) => {
    return h('Button', {
        props: {
            type: "primary",
            icon: 'edit',
            shape:"circle"
        },
        style: {
            'margin-right': '10px',

        },
        on: {
            click: () => {
                vm.selectVersion = param.row;
                vm.selectVersion._index = param.index;
                vm.fileUrl = param.row.fileurl;
                vm.fileSize = param.row.size;

                vm.appVersionForm.app_system = param.row.app_system;
                vm.appVersionForm.package = param.row.package;
                vm.appVersionForm.versioncode = param.row.versioncode;
                vm.appVersionForm.versionname = param.row.versionname;
                vm.appVersionForm.releasetime = new Date(param.row.releasetime.replace(/-/g, '/'));
                vm.appVersionForm.note = param.row.note;
                vm.showModal = true;
            }
        }
    })
}
const appVideoDeleteBtn = (h, param, vm) => {
    return h(
        "Poptip", {
            props: {
                confirm: true,
                title: "确定要删除版本信息?",
                transfer: true
            },
            style: {
                // 'width': '40px'
            },
            on: {
                "on-ok": () => {
                    vm.deleteAppVersion(param.row)
                }
            }
        }, [
            h('Button', {
                class: 'refund-btn',
                props: {
                    type: "error",
                    icon: 'trash-b',
                    disabled: param.row.is_use == '1',
                    shape:"circle"
                },
                on: {
                    click: () => {

                    }
                }
            })
        ]
    )
}

export default {
    computed: {
        user() {
            return this.$store.state.user.data
        }
    },
    data() {
        return {
            appVersionTableColumns: [{
                'title': '包名',
                'align': 'center',
                'key': 'package',
            }, {
                'title': '版本号',
                'align': 'center',
                'key': 'versioncode',
                'width': 90

            }, {
                'title': '版本名称',
                'align': 'center',
                'key': 'versionname',

            }, {
                'title': '大小',
                'align': 'center',
                'key': 'size',
                'width': 100

            }, {
                'title': '发布时间',
                'align': 'center',
                'key': 'releasetime',
                'width': 180

            }, {
                'title': '系统',
                'align': 'center',
                'key': 'app_system',
                'width': 90

            }, {
                'title': '更新说明',
                'align': 'center',
                'key': 'note',
            }, {
                'title': '操作',
                'align': 'center',
                'key': 'action',
                'action': true,
                'width': 150

            }],
            searchKey: '',
            pageCount: 0,
            pageNum: 1,
            pageLoading: false,
            showModal: false,
            modalLoading: true,
            appVersionList: [],
            selectVersion: '',
            fileSize: '',
            fileUrl: '',
            uploadFileData:{},
            isUploading:false,
            uploadProgress: 0,
            appVersionForm: {
                app_system: 'ANDROID',
                package: 'buddhism.maxmac.outsource',
                versioncode: '',
                versionname: '',
                releasetime: new Date(),
                note: ''
            },
            appVersionFormRules: {
                app_system: [{
                    required: true,
                    message: '请选择一个系统',
                    trigger: 'change'
                }],
                versioncode: [{
                    required: true,
                    validator:validate.versioncode,
                    trigger: 'blur'
                }],
                versionname: [{
                    required: true,
                    message: '请输入版本名称',
                    trigger: 'blur'
                }],
                package: [{
                    required: true,
                    message: '请输入包名',
                    trigger: 'blur'
                }],
                note: [{
                    required: true,
                    message: '请输入说明',
                    trigger: 'blur'
                }],
                releasetime: [{
                    required: true,
                    type: 'date',
                    message: '请选择日期',
                    trigger: 'change'
                }],
            },
        }
    },
    methods: {
        /**
         * @param {Boolean} type
         * 设置确定按钮loading动画，传True或者False
         */
        changeLoadingStatus(type) {
            if (!type) {
                this.modalLoading = false;
            }
            this.$nextTick(() => {
                this.modalLoading = true;
            });
        },
        // doSearch() {
        //     this.pageNum = 1;
        //     this.doGetAppVersionList();
        // },
        // clearSearch() {
        //     this.searchKey = '';
        //     this.pageNum = 1;
        //     this.doGetAppVersionList();
        // },
        changePage(num) {
            this.pageNum = num;
            this.doGetAppVersionList();
            document.querySelector('.single-page-con').scrollTo(0, 0)
        },
        doGetAppVersionList() {
            if (this.pageLoading) return
            this.pageLoading = true;
            this.http.post(this.postUrl.doGetAppVersionListUrl, {
                token: this.user.tokenList[0],
                pageNum: this.pageNum,
                pageSize: 20,
                key_word: this.searchKey
            }).then((data) => {
                console.log(data);
                if (data.code > -1) {
                    this.pageCount = data.data.totalRow;
                    this.appVersionList = JSON.parse(JSON.stringify(data.data.list));
                } else {
                    this.errorHandle(data.msg)
                }
            }, () => {
                this.errorHandle()
            }).then(() => {
                this.pageLoading = false;
            })
        },
        clickOK() {
            // if(!this.fileUrl){
            //     this.$Notice.warning({
            //         title:'请先上传文件！'
            //     })
            //     return
            //
            // }
            this.changeLoadingStatus(true)
            this.$refs.appVersionForm.validate(valid => {
                if (!valid) {
                    this.changeLoadingStatus(false)
                    return
                }
                let postData = JSON.parse(JSON.stringify(this.appVersionForm));
                postData.token = this.user.tokenList[0];
                postData.fileurl = this.fileUrl;
                postData.size = this.fileSize;
                postData.releasetime = this.appVersionForm.releasetime.getTime();
                if (this.selectVersion) {
                    postData.uuid = this.selectVersion.uuid;
                }
                this.http.post(this.postUrl.doAddOrEditAppVersion, postData).then((data) => {
                    if (data.code > -1) {
                        this.$Notice.success({
                            title: this.selectVersion ? '修改成功！' : '新增成功！'
                        })
                        this.showModal = false;
                        this.doGetAppVersionList();
                    } else {
                        this.errorHandle(data.msg)
                    }
                    this.changeLoadingStatus(false)

                }, () => {
                    this.errorHandle()
                    this.changeLoadingStatus(false)

                })
            })
        },
        deleteAppVersion(param) {
            this.http.post(this.postUrl.delectAppVersion, {
                token: this.user.tokenList[0],
                uuid: param.uuid
            }).then((data) => {
                if (data.code > -1) {
                    this.$Notice.success({
                        title: '操作成功！',
                    })
                    this.doGetAppVersionList()
                } else {
                    this.errorHandle(data.msg)
                }
            }, () => {
                this.errorHandle()
            })
        },
        recommendVideoTagChange(e) {
            console.log(e);
        },
        selectAppSystemChange(e) {
            if(this.fileUrl){
                this.fileUrl = ''
            }
            if(this.fileSize){
                this.fileSize = ''
            }
            if (e === 'IOS') {
                this.appVersionForm.package = 'com.sona-acoustics.sona-xpqh'
            } else {
                this.appVersionForm.package = 'buddhism.maxmac.outsource'

            }
        },
        bytesToSize(bytes) {
            if (!bytes || bytes == '0') return '0 B';
            bytes = Number(bytes) * 1000
            var k = 1024;

            let sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];

            let i = Math.floor(Math.log(bytes) / Math.log(k));

            return (bytes / Math.pow(k, i)).toFixed(2) + ' ' + sizes[i];
        },
        uploadSuccess(data) {
            if (data.code > -1) {
                this.fileUrl = data.data;
            } else {
                this.errorHandle(data.msg);
            }
            this.isUploading = false;
        },
        uploadError(e) {
            console.log("error", e);
            this.isUploading = false;
            this.errorHandle();
        },
        beforeUpload(file) {
            this.uploadProgress = 0;
            this.isUploading = true;
            this.fileSize = file.size/1000;
            console.log(this.fileSize);
            return true;
        },
        uploadProgressFunc(event) {
            this.uploadProgress = Math.round(event.percent);
        },
        handleFormatError() {
            this.isUploading = false;
            this.errorHandle("请选择正确的安装包文件！");
        },
        createFileUploadData(){
            //上传图片
            let uploadFileData = {
                token: this.user.tokenList[0],
                type: 1,
                app_key: this.http.app_key,
                timestamp: "2017-09-26 15:52:28"
            }
            let uploadFileDataSign = this.http.getSign({
                type: 1,
                token: this.user.tokenList[0]
            });
            uploadFileData.sign = uploadFileDataSign;
            this.uploadFileData = uploadFileData;
        },
    },
    created() {
        this.appVersionTableColumns.forEach(item => {
            if (item.action) {
                item.render = (h, param) => {
                    return h('div', [
                        appVideoEditBtn(h, param, this),
                        appVideoDeleteBtn(h, param, this)
                    ])
                };

            }
            if (item.key == 'app_system') {
                item.render = (h, param) => {
                    return h('Icon', {
                        props: {
                            type: param.row.app_system == 'IOS' ? 'social-apple' : 'social-android',
                            color: param.row.app_system == 'IOS' ? '' : '#6ab344',
                            size: 20
                        }
                    })
                };
            }
            if (item.key == 'size') {
                item.render = (h, param) => {
                    // let formateSize = '0 KB';
                    // if (!param.row.size || param.row.size == '0') {
                    //     formateSize = '';
                    // } else {
                    //     let k = 1024;
                    //     let bytes = Number(param.row.size) * 1000;
                    //     let sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
                    //
                    //     let i = Math.floor(Math.log(bytes) / Math.log(k));
                    //
                    //     formateSize = (bytes / Math.pow(k, i)).toFixed(2) + ' ' + sizes[i];
                    // }

                    return h('span', this.bytesToSize(param.row.size))
                };
            }
        })
        if (this.user) {
            this.doGetAppVersionList()
            this.createFileUploadData()
        }
    },
    watch: {
        user(val, old) {
            if (!old && val) {
                this.doGetAppVersionList()
                this.createFileUploadData()

            }
        },
        showModal(val) {
            if (!val) {
                this.fileUrl = '';
                this.fileSize = '';
                setTimeout(() => {
                    this.appVersionForm = {
                        app_system: 'ANDROID',
                        package: 'buddhism.maxmac.outsource',
                        versioncode: '',
                        versionname: '',
                        releasetime: new Date(),
                        note: ''
                    }
                }, 300)
                this.$refs.appVersionForm.resetFields()

            }
        }

    }
}
